<template>
  <div class="container">
    <el-card class="box-card">
      <el-form ref="form" :model="form" label-width="80px" label-position="top" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="书名" prop="bookName">
              <el-input v-model="form.bookName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作者" prop="author">
              <el-input v-model="form.author" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input v-model="form.price" type="number" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存" prop="repositoryNum">
              <el-input v-model.number="form.repositoryNum" type="number" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出版社">
              <el-input v-model="form.publisher" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类别" prop="selectedCate">
              <el-select v-model="form.selectedCate" multiple placeholder="请选择" clearable>
                <el-option
                  v-for="item in categoryList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述">
              <el-input v-model="form.bookDes" type="textarea" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="图书图片">
              <el-upload
                ref="upload"
                action="#"
                list-type="picture-card"
                :auto-upload="false"
                :limit="4"
                :multiple="true"
                :on-exceed="handleOver"
                :before-upload="beforeAvatarUpload"
                :file-list="fileList"
                :on-change="handleChange"
                :data="client"
                :http-request="doUpload"
                :on-error="handleError"
                :on-success="success"
              >
                <i slot="default" class="el-icon-plus" />
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div>
                <div slot="file" slot-scope="{file}">
                  <img class="el-upload-list__item-thumbnail" :src="file.url">
                  <span class="el-upload-list__item-actions">
                    <span
                      class="el-upload-list__item-preview"
                      @click="handlePictureCardPreview(file)"
                    >
                      <i class="el-icon-zoom-in" />
                    </span>
                    <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                      <i class="el-icon-delete" />
                    </span>
                  </span>
                </div>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt>
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="upload">提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import { getClient, getFileNameUUID } from '@/api/upload'
import { getCategory } from '@/utils/book'

export default {
  data() {
    const validateRep = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error('请输入库存'))
      }
      if (value === 0 || value < 0) {
        return callback(new Error('库存数量应该大于0'))
      } else {
        if (parseInt(value, 10) === value) {
          return callback()
        } else {
          return callback(new Error('库存数量不能有小数'))
        }
      }
    }
    const validatePrice = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error('请输入价格'))
      }
      if (value === 0 || value < 0 || value === '0') {
        return callback(new Error('价格应该大于0'))
      } else {
        return callback()
      }
    }
    return {

      dialogVisible: false,
      dialogImageUrl: '',
      // 上传的图书图片数组
      fileList: [],

      imgNames: [],
      form: {
        // 选中的category数组
        selectedCate: '',
        bookName: '',
        repositoryNum: '',
        bookDes: '',
        author: '',
        publisher: '',
        price: '',
        bookImgs: [],
        categories: []
      },
      getCategoryForm: {
        current: 1,
        size: 99,
        orderType: 0
      },
      client: getClient(),
      rules: {
        bookName: [{ required: true, trigger: 'blur', message: '请输入图书名称' }],
        author: [{ required: true, trigger: 'blur', message: '请输入图书作者' }],
        price: [{ required: true, trigger: 'change', validator: validatePrice }],
        repositoryNum: [{ required: true, trigger: 'change', validator: validateRep }],
        selectedCate: [{ required: true, message: '请选择图书类别', trigger: 'blur' }]
      }
    }
  },
  computed: {
    categoryList() {
      return this.$store.getters.categoryList
    }
  },
  created() {
    this.checkCategory()
  },
  methods: {

    async checkCategory() {
      if (this.categoryList && this.categoryList.length > 0) {
        // console.log('具有categories');
      } else {
        getCategory(this.getCategoryForm).then(res => {
          this.$store.commit('book/SET_CATEGORYLIST', res.object.records)
        })
      }
    },
    // 文件列表删除
    handleRemove(file) {
      const arr = this.fileList.filter(element => {
        return element.uid !== file.uid
      })
      this.fileList = arr
    },

    // 文件预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 文件数量超出限制
    handleOver(file, fileList) {
      this.$message.error('最多上传4个图片')
    },

    // 点击上传按钮
    upload() {
      // 1.先验证表单数据
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 2.验证图片是否存在
          if (this.fileList && this.fileList.length > 0) {
            // 3.上传图书图片
            // console.log(this.$refs.upload.submit());
            this.$refs.upload.submit()
            // console.log(this.imgNames.length, this.fileList.length);
          } else {
            this.$message.error('请添加图书图片')
          }
        } else {
          return false
        }
      })
    },

    handleError(err, file, fileList) {
      console.log(err)
    },
    // 进行图片的后缀验证
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 或者 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    handleChange(file, fileList) {
      this.fileList = fileList
    },
    doUpload(file) {
      // console.log(fileList, "aaaaaaaaaaaaa");

      try {
        const fileName = getFileNameUUID() + file.file.name
        this.client.put(fileName, file.file).then(res => {
          // console.log('成功了')
          // 每一张图片上传成功保留imgName
          // console.log();
          this.imgNames.push(fileName)
          if (this.imgNames.length === this.fileList.length) {
            // 图片上传成功，进行添加图书
            console.log(this.imgNames.length)
            console.log(this.fileList.length)
            this.doAddBook()
            // console.log(this.doAddBook);
          }
        }).catch(() => {
          this.$notify.error({
            title: '错误',
            message: '添加图书失败'
          })
        })
      } catch (e) {
        console.log(e)
      }
    },
    success() {
      this.$message('成功了')
    },
    doAddBook() {
      const imgArr = []
      this.imgNames.forEach(element => {
        imgArr.push({ 'imgName': element })
        // this.form.bookImgs.push({ 'imgName': element })
      })
      this.form.bookImgs = imgArr

      const cateArr = []
      this.form.selectedCate.forEach(element => {
        cateArr.push({ 'id': element })
        // this.form.categories.push({ 'id': element })
      })
      this.form.categories = cateArr

      this.$store.dispatch('book/addBook', this.form).then(res => {
        this.$notify({
          title: '成功',
          message: '添加图书成功',
          type: 'success'
        })
        this.fileList = []
        this.imgNames = []
        this.$router.push(this.$route.fullPath + '?' + new Date().getTime())
      }).catch(() => {
        this.$notify({
          title: '失败',
          message: '添加图书失败',
          type: 'error'
        })
        this.fileList = []
        this.imgNames = []
      })
    }

  }

}
</script>
<style lang="scss" scoped>
.container {
  margin-top: 50px;
  margin-left: 100px;
  margin-right: 100px;
  // background-color: gray;
}
</style>
